<template>
  <div class="rengongzhineng-chat-container">
    <div class="chat-layout">
      <!-- 会话列表侧边栏 -->
      <div class="sessions-sidebar" :class="{ 'collapsed': isSidebarCollapsed }" ref="sidebarRef">
        <div class="sidebar-header">
          <div class="sidebar-title">
            <h2 v-if="!isSidebarCollapsed">会话历史</h2>
            <a-button type="text" @click="toggleSidebar" class="toggle-sidebar-btn">
              <template #icon>
                <span class="iconfont"
                  :class="isSidebarCollapsed ? 'icon-zhankaishousuo' : 'icon-zhankaishousuo'"></span>
              </template>
            </a-button>
          </div>
          <a-button v-if="!isSidebarCollapsed" type="primary" @click="createNewSession" class="new-session-btn">
            <template #icon>
              <PlusOutlined />
            </template>
            新建会话
          </a-button>
        </div>
        <div v-if="!isSidebarCollapsed" class="sessions-list">
          <div v-for="session in sessions" :key="session.id"
            :class="['session-item', { 'active': session.id === currentSessionId }]" @click="switchSession(session.id)">
            <div class="session-content">
              <div class="session-title">
                <div class="session-title-text"> {{ getSessionTitle(session) }}</div>
                <div class="session-actions">
                  <a-dropdown :trigger="['click']">
                    <span class="iconfont icon-gengduo" @click.stop.prevent="" style="
                                cursor: pointer;
                                color: #266fe8;
                                font-size: 13px;
                                margin-right: 5px;
                            "></span>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item key="edit" @click.stop="handleEditSessionDescription(session)">
                          <EditOutlined />
                          编辑描述
                        </a-menu-item>
                        <a-menu-item v-if="sessions.length > 1" key="delete" @click.stop="deleteSession(session.id)">
                          <DeleteOutlined />
                          删除会话
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </div>
              <div class="session-meta">
                <span class="message-count">{{ session.messages.length }} 条消息</span>
                <span class="session-time">{{ formatSessionTime(session.lastUpdated) }}</span>
              </div>
            </div>

          </div>
        </div>
        <!-- 添加蒙层 -->
        <div v-show="isSidebarCollapsed || isSidebarAnimating" class="sidebar-cover" @click="toggleSidebar">
          <span class="sidebar-cover-text">展开会话历史</span>
        </div>
      </div>

      <!-- 聊天主区域 -->
      <div class="chat-main">
        <div class="chat-header">
          <h1>
            <span class="iconfont icon-rengongzhineng"></span>
            AI 助手
          </h1>
          <p class="subtitle">与AI助手对话，获得智能帮助</p>
        </div>

        <div class="chat-wrapper">
          <div class="chat-messages" ref="messagesContainer">
            <div v-for="(message, index) in messages" :key="index"
              :class="['message', message.role === 'user' ? 'user-message' : 'rengongzhineng-message']">
              <div class="message-content">
                <div class="avatar" v-if="message.role === 'assistant' && !isLoading">
                  <span class="iconfont icon-rengongzhineng"></span>
                </div>
                <div class="content">
                  <div class="text" :class="{ 'markdown-content': message.role === 'assistant' }"
                    v-html="message.role === 'assistant' ? renderMarkdown(message.content) : formatMessage(message.content)">
                  </div>
                </div>
                <div class="avatar user-avatar" v-if="message.role === 'user'">
                  <span class="iconfont icon-user"></span>
                </div>
              </div>
            </div>
            <div v-if="isLoading" class="message rengongzhineng-message">
              <div class="message-content">
                <div class="avatar">
                  <span class="iconfont icon-rengongzhineng"></span>
                </div>
                <div class="content" v-if="typingContent">
                  <!-- 打字机效果显示AI回复 -->
                  <div class="text markdown-content" v-html="renderMarkdown(typingContent)"></div>
                </div>
                <div v-else>
                  <div class="thinking">
                    <div class="thinking-indicator">
                      <span class="dot"></span>
                      <span class="dot"></span>
                      <span class="dot"></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="chat-input-area">
            <div class="input-container">
              <a-textarea v-model:value="inputMessage" placeholder="输入消息与AI助手对话..."
                :auto-size="{ minRows: 3, maxRows: 6 }" @pressEnter="handleSend" />
              <a-button v-if="!isLoading" type="primary" @click="handleSend" :disabled="!inputMessage.trim()">
                发送
              </a-button>
              <a-button v-else type="primary" @click="handleStop">
                <template #icon>
                  <PauseOutlined />
                </template>
                停止回复
              </a-button>
            </div>
            <div class="input-hint">
              按 Enter 发送，Shift + Enter 换行
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 描述编辑模态框 -->
    <a-modal v-model:open="descriptionModal.visible" title="编辑会话" @ok="handleDescriptionOk"
      @cancel="descriptionModal.visible = false" okText="确定" cancelText="取消">
      <a-form layout="vertical">
        <a-form-item label="会话标题">
          <a-input v-model:value="descriptionModal.title" placeholder="请输入会话标题" />
        </a-form-item>
        <a-form-item label="会话描述">
          <a-textarea v-model:value="descriptionModal.value" placeholder="请输入会话描述，用于指导AI回复..."
            :auto-size="{ minRows: 3, maxRows: 6 }" />
        </a-form-item>
      </a-form>
      <div style="margin-top: 10px; font-size: 12px; color: #666;">
        会话描述仅在调用AI接口时作为上下文发送，不会显示在会话历史中。
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, onUnmounted, computed, onActivated, } from "vue";
import MarkdownIt from "markdown-it";
import { PlusOutlined, DeleteOutlined, PauseOutlined, EditOutlined } from "@ant-design/icons-vue";
import { useBaseStore } from "@/renderer/store/useBaseStore";
import { useRoute } from "vue-router";

// 初始化Markdown解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
});

// 定义消息类型
interface Message {
  role: "user" | "assistant" | "system";
  content: string;
}

// 定义会话类型
interface Session {
  id: string;
  title: string;
  messages: Message[];
  lastUpdated: number;
  description?: string; // 添加description字段
}

const messages = ref<Message[]>([
  {
    role: "assistant",
    content: "您好！我是您的AI助手，有什么我可以帮您的吗？"
  }
]);
const inputMessage = ref("");
const isLoading = ref(false);
const messagesContainer = ref<HTMLElement | null>(null);
const typingContent = ref(""); // 用于打字机效果的内容
const typingTimer = ref<number | null>(null); // 打字机定时器
const currentTypingTarget = ref(""); // 当前打字机的目标文本

// 会话相关状态
const sessions = ref<Session[]>([]);
const currentSessionId = ref<string>("");


// 格式化会话时间
const formatSessionTime = (timestamp: number) => {
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (days === 0) {
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } else if (days === 1) {
    return '昨天';
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return `${date.getMonth() + 1}-${date.getDate()}`;
  }
};

// 获取会话标题
const getSessionTitle = (session: Session) => {
  if (session.title) return session.title;

  // 如果没有标题，从第一条消息生成标题
  if (session.messages.length > 0) {
    const firstUserMessage = session.messages.find(msg => msg.role === 'user');
    if (firstUserMessage) {
      // 取消息前15个字符作为标题
      return firstUserMessage.content.substring(0, 15) + (firstUserMessage.content.length > 15 ? '...' : '');
    }
  }

  return '新会话';
};

// 格式化普通文本消息（处理换行等）
const formatMessage = (content: string) => {
  return content.replace(/\n/g, '<br>');
};

// 渲染Markdown内容
const renderMarkdown = (content: string) => {
  if (!content) return '';
  return md.render(content);
};

// 打字机效果函数
const typeWriter = (targetText: string) => {
  // 如果目标文本发生变化，更新当前目标
  if (targetText !== currentTypingTarget.value) {
    currentTypingTarget.value = targetText;
  }

  const currentLength = typingContent.value.length;
  const targetLength = currentTypingTarget.value.length;

  // 清除之前的定时器
  if (typingTimer.value) {
    clearTimeout(typingTimer.value);
    typingTimer.value = null;
  }

  // 如果还没达到目标长度，继续打字
  if (currentLength < targetLength) {
    typingContent.value = currentTypingTarget.value.substring(0, currentLength + 1);
    // 滚动到底部
    scrollToBottom();

    // 设置下一个字符的定时器
    typingTimer.value = window.setTimeout(() => {
      typeWriter(currentTypingTarget.value);
    }, 20); // 20ms 间隔，模拟打字效果
  }
};

// 创建新会话
const createNewSession = async () => {
  // 保存当前会话
  if (currentSessionId.value) {
    await saveCurrentSession();
  }

  // 创建新的会话
  const newSession: Session = {
    id: Date.now().toString(),
    title: "",
    description: "", // 添加description字段
    messages: [
      {
        role: "assistant",
        content: "您好！我是您的AI助手，有什么我可以帮您的吗？"
      }
    ],
    lastUpdated: Date.now()
  };

  try {
    // 通过Express API创建新会话
    const response = await fetch('http://localhost:32068/api/sessions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(newSession),
    });

    const result = await response.json();
    if (result.code === 201) {
      // 添加到会话列表
      sessions.value.unshift(result.data);

      // 设置为当前会话
      currentSessionId.value = result.data.id;
      messages.value = [...result.data.messages];
    } else {
      throw new Error(result.error || "创建会话失败");
    }
  } catch (error: any) {
    console.error("创建会话失败:", error);
    // 如果API创建失败，仍然在前端创建会话
    sessions.value.unshift(newSession);
    currentSessionId.value = newSession.id;
    messages.value = [...newSession.messages];
  }

  // 滚动到底部
  await nextTick();
  scrollToBottom();
};

// 切换会话
const switchSession = async (sessionId: string) => {
  // 如果点击的是当前会话，不处理
  if (sessionId === currentSessionId.value) return;

  // 在切换会话前先停止当前回复
  if (isLoading.value) {
    handleStop();
    // 等待一小段时间确保停止操作完成
    await new Promise(resolve => setTimeout(resolve, 50));
  }

  // 保存当前会话
  if (currentSessionId.value) {
    await saveCurrentSession();
  }

  // 查找目标会话
  const session = sessions.value.find(s => s.id === sessionId);
  if (session) {
    currentSessionId.value = sessionId;
    messages.value = [...session.messages];

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
};

// 删除会话
const deleteSession = async (sessionId: string) => {
  if (sessions.value.length <= 1) {
    console.warn("至少需要保留一个会话");
    return;
  }

  // 确认删除
  if (!confirm(`确定要删除这个会话吗？`)) {
    return;
  }

  try {
    // 通过Express API删除会话
    const response = await fetch(`http://localhost:32068/api/sessions/${sessionId}`, {
      method: 'DELETE',
    });

    const result = await response.json();
    if (result.code === 200) {
      // 从会话列表中移除
      const sessionIndex = sessions.value.findIndex(s => s.id === sessionId);
      if (sessionIndex !== -1) {
        sessions.value.splice(sessionIndex, 1);
      }

      // 如果删除的是当前会话，切换到第一个会话
      if (sessionId === currentSessionId.value) {
        if (sessions.value.length > 0) {
          const firstSession = sessions.value[0];
          currentSessionId.value = firstSession.id;
          messages.value = [...firstSession.messages];

          // 滚动到底部
          await nextTick();
          scrollToBottom();
        } else {
          // 如果没有会话了，创建新会话
          await createNewSession();
        }
      }
      console.log("会话删除成功");
    } else {
      throw new Error(result.error || "删除会话失败");
    }
  } catch (error: any) {
    console.error("删除会话失败:", error);
    alert("删除会话失败: " + (error?.message || "未知错误"));
  }
};

// 保存当前会话
const saveCurrentSession = async () => {
  if (!currentSessionId.value) return;

  const sessionIndex = sessions.value.findIndex(s => s.id === currentSessionId.value);
  if (sessionIndex !== -1) {
    // 更新会话数据
    // 创建纯净的可序列化对象，避免DataCloneError
    const sessionToSave = {
      id: sessions.value[sessionIndex].id,
      title: sessions.value[sessionIndex].title,
      messages: messages.value.map(msg => ({
        role: msg.role,
        content: msg.content
      })),
      lastUpdated: Date.now()
    };

    // 如果会话没有标题，尝试从第一条用户消息生成标题
    if (!sessionToSave.title) {
      const firstUserMessage = sessionToSave.messages.find(msg => msg.role === 'user');
      if (firstUserMessage) {
        sessionToSave.title = firstUserMessage.content.substring(0, 15) +
          (firstUserMessage.content.length > 15 ? '...' : '');
      }
    }

    // 更新内存中的会话数据
    sessions.value[sessionIndex] = {
      ...sessions.value[sessionIndex],
      ...sessionToSave
    };

    // 通过Express API更新会话
    try {
      const response = await fetch(`http://localhost:32068/api/sessions/${sessionToSave.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sessionToSave),
      });

      const result = await response.json();
      if (result.code !== 200) {
        throw new Error(result.error || "更新会话失败");
      }
      console.log("会话保存成功");
    } catch (error: any) {
      console.error("保存会话失败:", error);
      console.error("失败的会话数据:", sessionToSave);
      // 显示更详细的错误信息
      const errorMessage = error?.message || error?.toString() || "未知错误";
      console.error("错误详情:", errorMessage);
    }
  }
};

// 停止回复功能
const stopReply = ref(false);
const handleStop = () => {
  stopReply.value = true;
  isLoading.value = false;

  // 清除打字机定时器
  if (typingTimer.value) {
    clearTimeout(typingTimer.value);
    typingTimer.value = null;
  }

  // 将当前打字内容设置为最终内容
  if (messages.value.length > 0) {
    const lastMessage = messages.value[messages.value.length - 1];
    if (lastMessage.role === 'assistant') {
      lastMessage.content = typingContent.value;
    }
  }
};
const baseStore = useBaseStore();
// 发送消息
const handleSend = async (e: KeyboardEvent | MouseEvent) => {
  // 从 store 中获取 qwenPlusApiKey

  const qwenPlusApiKey = computed(() => baseStore.data.qwenPlusApiKey);
  // 如果是Enter键且没有Shift键，则发送消息
  if (e instanceof KeyboardEvent && e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
  } else if (e instanceof KeyboardEvent && e.key === 'Enter' && e.shiftKey) {
    // 如果是Shift+Enter，则换行，不发送
    return;
  }

  if (!inputMessage.value.trim() || isLoading.value) {
    return;
  }

  // 添加用户消息
  const userMessage: Message = {
    role: "user",
    content: inputMessage.value.trim()
  };

  messages.value.push(userMessage);
  const userContent = inputMessage.value;
  inputMessage.value = "";

  try {
    isLoading.value = true;
    typingContent.value = ""; // 重置打字机内容
    currentTypingTarget.value = ""; // 重置打字机目标内容

    // 滚动到底部
    await nextTick();
    scrollToBottom();

    // 获取当前会话
    const currentSession = sessions.value.find(s => s.id === currentSessionId.value);

    // 准备历史记录，保留系统消息
    let historyForAPI = messages.value.map(m => ({ role: m.role, content: m.content }));

    // 如果当前会话有描述，且历史记录中没有系统消息，则在历史记录开头添加系统消息
    if (currentSession?.description && !messages.value.some(m => m.role === 'system')) {
      historyForAPI = [
        { role: "system", content: currentSession.description },
        ...historyForAPI
      ];
    }

    // 调用后端接口
    const response = await fetch('http://localhost:32068/chat-stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        qwenPlusApiKey: qwenPlusApiKey.value,
        prompt: userContent,
        history: historyForAPI // 使用添加了描述的历史记录
      })
    });

    if (!response.body) {
      throw new Error('响应体为空');
    }

    // 添加AI消息
    const aiMessage: Message = {
      role: "assistant",
      content: ""
    };
    messages.value.push(aiMessage);

    // 滚动到底部
    await nextTick();
    scrollToBottom();

    // 处理流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let accumulatedContent = ""; // 累积的内容用于打字机效果

    try {
      while (true) {
        // 检查是否应该停止
        if (stopReply.value) {
          stopReply.value = false;
          break;
        }

        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        accumulatedContent += chunk;

        // 更新打字机目标文本
        typeWriter(accumulatedContent);
      }

      // 将完整内容设置到消息中
      aiMessage.content = accumulatedContent;
    } finally {
      reader.releaseLock();
    }
  } catch (error) {
    console.error("发送消息时出错:", error);
    if (!stopReply.value) {
      const errorMessage = "抱歉，我在处理您的请求时遇到了问题，请稍后重试。";
      messages.value.push({
        role: "assistant",
        content: errorMessage
      });

      // 错误消息也使用打字机效果
      typeWriter(errorMessage);
    }
  } finally {
    isLoading.value = false;
    stopReply.value = false; // 重置停止标志
    // 清除打字机定时器，确保不会继续触发滚动
    if (typingTimer.value) {
      clearTimeout(typingTimer.value);
      typingTimer.value = null;
    }
    await nextTick();
    scrollToBottom();

    // 保存当前会话
    await saveCurrentSession();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
};

// 初始化数据库和加载会话
const initDatabase = async () => {
  try {
    // 通过Express API获取所有会话
    const response = await fetch('http://localhost:32068/api/sessions');
    const result = await response.json();
    console.log('Sessions API Response:', result);

    // 使用API返回的数据
    if (result.data && Array.isArray(result.data)) {
      sessions.value = result.data;
    } else {
      sessions.value = [];
    }

    // 按最后更新时间排序
    sessions.value.sort((a, b) => b.lastUpdated - a.lastUpdated);

    // 如果没有会话，创建默认会话
    if (sessions.value.length === 0) {
      await createNewSession();
    } else {
      // 加载最新的会话
      const latestSession = sessions.value[0];
      currentSessionId.value = latestSession.id;
      messages.value = [...latestSession.messages];
    }
  } catch (error) {
    console.error("通过API获取会话数据失败:", error);
    // 如果API获取失败，创建默认会话
    await createNewSession();
  }
};

// 获取路由对象
const route = useRoute();

// 组件挂载后滚动到底部
onMounted(async () => {
  await initDatabase();
  scrollToBottom();
});

onActivated(async () => {
  // 检查是否从Conversation路由跳转过来（通过路由守卫设置的参数）
  if (route.query.fromConversation === 'true') {
    await initDatabase();
    scrollToBottom();
    // 清除参数，避免重复触发
    delete route.query.fromConversation;
  }
});

// 组件卸载前清理定时器和保存会话
onUnmounted(async () => {
  if (typingTimer.value) {
    clearTimeout(typingTimer.value);
    typingTimer.value = null;
  }

  // 保存当前会话
  if (currentSessionId.value) {
    await saveCurrentSession();
  }


});

// 用于描述编辑的Modal状态
const descriptionModal = ref({
  visible: false,
  session: null as Session | null,
  value: "",
  title: "" // 添加标题字段
});

const showDescriptionModal = (session: Session) => {
  descriptionModal.value.session = session;
  descriptionModal.value.value = session.description || "";
  descriptionModal.value.title = session.title || ""; // 初始化标题
  descriptionModal.value.visible = true;
};

const handleDescriptionOk = () => {
  if (descriptionModal.value.session) {
    descriptionModal.value.session.description = descriptionModal.value.value;
    descriptionModal.value.session.title = descriptionModal.value.title; // 保存标题
    // 更新会话的最后更新时间
    descriptionModal.value.session.lastUpdated = Date.now();
    // 保存会话
    saveSessionDescription(descriptionModal.value.session);
  }
  descriptionModal.value.visible = false;
};

const handleEditSessionDescription = (session: Session) => {
  showDescriptionModal(session);
};

const saveSessionDescription = async (session: Session) => {
  try {
    // 通过Express API更新会话描述
    const response = await fetch(`http://localhost:32068/api/sessions/${session.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(session),
    });

    const result = await response.json();
    if (result.code !== 200) {
      throw new Error(result.error || "更新会话失败");
    }
    console.log("会话描述保存成功");
  } catch (error: any) {
    console.error("保存会话描述失败:", error);
  }
};

// 添加侧边栏收缩状态
const isSidebarCollapsed = ref(false);
const isSidebarAnimating = ref(false); // 添加动画状态
const sidebarRef = ref<HTMLElement | null>(null);

// 切换侧边栏收缩状态
const toggleSidebar = () => {
  isSidebarAnimating.value = true; // 开始动画
  isSidebarCollapsed.value = !isSidebarCollapsed.value;

  // 动画结束后清除动画状态
  setTimeout(() => {
    isSidebarAnimating.value = false;
  }, 300); // 与CSS transition时间保持一致
};

</script>

<style scoped>
.rengongzhineng-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px;
  background-color: var(--background-color);
  font-size: 14px;
}

.chat-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
  border-radius: var(--border-radius);
  border: 1px solid var(--border-color);
  box-shadow: var(--shadow);
  background: var(--surface-color);
  transition: all 0.3s ease;
}

.sessions-sidebar {
  width: 255px;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  background-color: var(--background-color);
  transition: all 0.3s ease;
  overflow: hidden;
  position: relative;
  /* 添加相对定位 */
}

.sessions-sidebar.collapsed {
  width: 40px;
  border-right: none;
}

/* 侧边栏蒙层样式 */
.sidebar-cover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(5px);
  z-index: 999;
  cursor: pointer;
  font-size: 16px;
  color: rgba(0, 0, 0, 0.7);
  user-select: none;
}

.sidebar-cover-text {
  writing-mode: vertical-lr;
  font-size: 15px;
  color: rgb(38, 111, 232);
  letter-spacing: 5px;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
}

.sidebar-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  flex: 1;
}

.toggle-sidebar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-session-btn {
  width: 100%;
  margin-top: 12px;
}

.sessions-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.session-item {
  padding: 12px;
  border-radius: var(--border-radius);
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid transparent;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.session-content {
  flex: 1;
  min-width: 0;
}

.session-item:hover {
  background-color: var(--hover-color);
}

.session-item.active {
  background-color: var(--primary-light-color);
  border-color: var(--primary-color);
  color: white;
  font-weight: 600;
}

.session-title {
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.session-title-text {
  max-width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.session-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: var(--text-secondary);
}

.session-actions {
  display: flex;
  gap: 4px;
}

.more-actions-btn {
  color: var(--text-secondary);
  padding: 4px;
}

.more-actions-btn:hover {
  color: var(--primary-color);
  background-color: transparent;
}

.edit-description-btn,
.delete-session-btn {
  color: var(--text-secondary);
  padding: 4px;
}

.edit-description-btn:hover,
.delete-session-btn:hover {
  color: var(--primary-color);
  background-color: transparent;
}

.delete-session-btn:hover {
  color: #ff4d4f;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 12px 20px;
  position: relative;
}

.chat-header h1 {
  font-size: 20px;
  color: var(--text-primary);
  margin-bottom: 6px;
}

.chat-header .subtitle {
  color: var(--text-secondary);
  font-size: 13px;
  margin-bottom: 16px;
}

.chat-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0 16px 16px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message {
  display: flex;
  flex-direction: column;
}

.message-content {
  display: flex;
  gap: 10px;
  max-width: 90%;
}

.rengongzhineng-message .message-content {
  align-items: flex-start;
}

.user-message .message-content {
  align-self: flex-end;
}

.avatar {
  flex-shrink: 0;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
}

.user-avatar {
  display: none;
}

.user-message .avatar {
  background-color: var(--primary-light-color);
  order: 2;
}

.user-message .user-avatar {
  display: flex;
  background-color: var(--primary-light-color);
  order: 1;
  margin-left: 10px;
}

.content {
  flex: 1;
}

.text {
  padding: 10px 14px;
  border-radius: 16px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 14px;
}

.rengongzhineng-message .text {
  background-color: #f0f9ff;
  border: 1px solid var(--border-color);
  border-top-left-radius: 4px;
}

.user-message .text {
  background-color: var(--primary-color);
  color: white;
  border-top-right-radius: 4px;
}

/* Markdown内容样式 */
.markdown-content {
  background-color: transparent !important;
  color: var(--text-primary);
  border: none !important;
  padding: 0 !important;
  white-space: normal;
}

.markdown-content :deep(*) {
  color: var(--text-primary);
  line-height: 1.6;
}

.markdown-content :deep(h1),
.markdown-content :deep(h2),
.markdown-content :deep(h3) {
  margin: 16px 0 10px 0;
  font-weight: 600;
}

.markdown-content :deep(h1) {
  font-size: 22px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 8px;
}

.markdown-content :deep(h2) {
  font-size: 20px;
}

.markdown-content :deep(h3) {
  font-size: 18px;
}

.markdown-content :deep(p) {
  margin: 10px 0;
}

.markdown-content :deep(ul),
.markdown-content :deep(ol) {
  padding-left: 24px;
  margin: 10px 0;
}

.markdown-content :deep(li) {
  margin: 6px 0;
}

.markdown-content :deep(code) {
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 13px;
}

.markdown-content :deep(pre) {
  background-color: #f8f8f8;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  padding: 12px;
  overflow-x: auto;
  margin: 12px 0;
}

.markdown-content :deep(pre code) {
  background: none;
  padding: 0;
}

.markdown-content :deep(blockquote) {
  border-left: 4px solid var(--primary-color);
  padding: 1px 0 1px 16px;
  margin: 12px 0;
  color: var(--text-secondary);
}

.markdown-content :deep(a) {
  color: var(--primary-color);
  text-decoration: none;
}

.markdown-content :deep(a:hover) {
  text-decoration: underline;
}

.markdown-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.markdown-content :deep(th),
.markdown-content :deep(td) {
  border: 1px solid var(--border-color);
  padding: 8px 12px;
  text-align: left;
}

.markdown-content :deep(th) {
  background-color: #f0f9ff;
  font-weight: 600;
}

.markdown-content :deep(img) {
  max-width: 100%;
  border-radius: 6px;
  margin: 8px 0;
}

.typing-indicator {
  display: flex;
  padding: 10px 14px;
  gap: 5px;
}

.typing-indicator span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: var(--primary-light-color);
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

.thinking {
  display: flex;
  align-items: center;
  padding: 10px 14px;
}

.thinking-indicator {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: var(--primary-color);
  margin: 0 3px;
  animation: thinking 1.5s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: -0.3s;
}

.dot:nth-child(2) {
  animation-delay: -0.15s;
}

@keyframes thinking {

  0%,
  80%,
  100% {
    transform: scale(0);
    opacity: 0.5;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}


.chat-input-area {
  border-top: 1px solid var(--border-color);
  padding: 14px 0;
}

.input-container {
  display: flex;
  gap: 10px;
  align-items: flex-end;
  padding: 0 16px;
}

.input-container :deep(.ant-input) {
  border-radius: var(--border-radius);
  resize: none;
  font-size: 14px;
}

.input-container :deep(.ant-btn) {
  height: auto;
  padding: 6px 14px;
  font-size: 14px;
}

.input-hint {
  font-size: 12px;
  color: var(--text-placeholder);
  margin-top: 6px;
  text-align: center;
  padding: 0 16px;
}
</style>
